package com.example.compose.ui.camera

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.ViewGroup
import androidx.camera.core.CameraSelector
import androidx.camera.core.FocusMeteringAction
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import com.example.compose.utils.toDp


@Composable
fun CameraPreview() {
    val lifecycleOwner = LocalLifecycleOwner.current
    val context = LocalContext.current
    val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
    val x = remember { mutableStateOf(0)}
    val y = remember { mutableStateOf(0)}
    val enable = remember { mutableStateOf(false)}
    Box(Modifier.fillMaxSize(),contentAlignment= Alignment.TopStart) {
        val onTouch = fun(x1:Float,y1:Float):Boolean{
            if(enable.value) return true
            enable.value = true
            Thread {
                Thread.sleep(500)
                enable.value = false
            }.start()
            x.value = x1.toInt()
            y.value = y1.toInt()
            return true
        }
        AndroidView(
            factory = { ctx ->
                val preview = PreviewView(context).apply {
                    this.scaleType = scaleType
                    layoutParams = ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    // Preview is incorrectly scaled in Compose on some devices without this
                    implementationMode = PreviewView.ImplementationMode.COMPATIBLE
                }
                cameraProviderFuture.addListener({
                    val cameraProvider = cameraProviderFuture.get()
                    bindPreview(
                        lifecycleOwner,
                        preview,
                        cameraProvider,
                        onTouch
                    )
                }, ContextCompat.getMainExecutor(ctx))
                preview
            },
            modifier = Modifier.fillMaxSize(),
        )
        Box(modifier = Modifier.size(100.dp).offset(x.value.toDp.dp - 50.dp,y.value.toDp.dp - 50.dp),contentAlignment= Alignment.Center){
            ClickEffect(enable.value)
        }

    }
}

@SuppressLint("ClickableViewAccessibility")
private fun bindPreview(
    lifecycleOwner: LifecycleOwner,
    previewView: PreviewView,
    cameraProvider: ProcessCameraProvider,
    onTouch:(Float,Float)-> Boolean
) {
    val preview = androidx.camera.core.Preview.Builder().build()
    val cameraSelector: CameraSelector = CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
        .build()
    preview.setSurfaceProvider(previewView.surfaceProvider)
    val camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview)
    previewView.setOnTouchListener { _, event ->
        val iMaskAct = event!!.action and MotionEvent.ACTION_MASK
        if (iMaskAct == MotionEvent.ACTION_UP) {
            camera.cameraControl.startFocusAndMetering(
                FocusMeteringAction.Builder(
                    previewView.meteringPointFactory.createPoint(event.x, event.y)
                ).build()
            )
            onTouch(event.x, event.y)
        }
        true
    }

}


